package utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketUtils {
    
    /**
     * Method creating a server socket on the specified port
     * @param port the port to create the socket
     * @return the ServerSocket object
     */
    public static ServerSocket createServerSocket(int port) {
        ServerSocket ret = null;
        try {
            ret = new ServerSocket(port);
        } catch (IOException e) {
            System.out.println(e);
        }       
        return ret;
    }
    
    /*
    public static void closeServerSocket(Socket connectSocket, ServerSocket server) {
        try {
            // Close the socket
            connectSocket.close();
            // Close the server socket
            server.close();
        } catch (IOException e) {
            System.out.println(e);
        }
    }*/
    
    public static void closeSocket(Socket socket){
        try {
            socket.close();
        } catch (IOException e) {
            System.out.println(e);
        }
    }
    
    /**
     * Write data in the specified socket
     * @param connectSocket the socket to write data in
     * @param data the data to write in the socket
     */
    public static void writeDataInSocket(Socket connectSocket, String data){
        try {
            Writer out = new BufferedWriter(new OutputStreamWriter(connectSocket.getOutputStream()));
            data += "\n";
            out.write(data);
            out.flush();
        } catch (IOException e) {
            System.out.println(e);
        }       
    }
    
    /**
     * Read data from the specified socket
     * @param clientSocket the socket to get the data from
     * @return the data readed from the socket
     */
    public static String readDataFromSocket(Socket clientSocket) {
        String ret = "";
        String temp = null;
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            while (in.ready()) {
                temp = in.readLine();
                if (temp != null) {
                    ret += temp + '\n';
                }
            }
        } catch (IOException e) {
            System.out.println(e);
        }
        return ret;
    }
}
